<template>
  <div class="ep-widget-panel-container">
    <div class="left-area">
      <div class="left-area-icon" :class="{ active: leftArea === 0 }">
        <m-icon name="line-qrcode" @click="leftArea = 0" />
      </div>
      <div class="left-area-icon" :class="{ active: leftArea === 1 }">
        <m-icon name="code" @click="leftArea = 1" />
      </div>
    </div>
    <div class="left-panel-container">
      <el-tabs v-if="leftArea === 0" v-model="leftTabs" stretch>
        <el-tab-pane name="basic">
          <template #label>
            <span>基础组件</span>
          </template>

          <div class="component-description-list">
            <div class="component-description-list-content">
              <div class="component-description-list-content-header">
                <span class="title">常用</span>
              </div>
              <draggable
                tag="div"
                class="widget-panel-fields"
                :list="basicFieldsFilter"
                item-key="type"
                :group="{ name: 'people', pull: 'clone', ghostClass: 'ghost', put: false }"
                :clone="handleFieldWidgetClone"
                :sort="false"
              >
                <template #item="{ element: el }">
                  <div class="widget-panel-fields-item" :title="el.name" @dblclick="addContainer(el)">
                    <div class="brief-snippet-inner">
                      <m-icon :name="el.icon" />
                      <div class="title">{{ el.name }}</div>
                    </div>
                  </div>
                </template>
              </draggable>
            </div>
            <div class="component-description-list-content">
              <div class="component-description-list-content-header">
                <span class="title">高级</span>
              </div>
              <draggable
                tag="div"
                class="widget-panel-fields"
                :list="complexFieldsFilter"
                item-key="type"
                :group="{ name: 'people', pull: 'clone', ghostClass: 'ghost', put: false }"
                :clone="handleFieldWidgetClone"
                :sort="false"
              >
                <template #item="{ element: el }">
                  <div class="widget-panel-fields-item" :title="el.name" @dblclick="addContainer(el)">
                    <div class="brief-snippet-inner">
                      <m-icon :name="el.icon" />
                      <div class="title">{{ el.name }}</div>
                    </div>
                  </div>
                </template>
              </draggable>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-tabs v-if="leftArea === 1" model-value="code" stretch>
        <el-tab-pane name="code">
          <template #label>
            <span>代码</span>
          </template>

          <div class="component-description-list-content-header">
            <span class="title">生成JSON</span>
          </div>

          <div class="component-code-json">
            <code-editor
              v-model="jsonContent"
              mode="json"
              :show-gutter="false"
              :max-lines="40"
              :font-size="12"
              readonly
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { ref, computed, getCurrentInstance } from 'vue'
import _ from 'lodash'
import draggable from '@marshallswain/vuedraggable'
import { basicFields, complexFields } from '@/config/widgetsConfig'

export default {
  components: {
    draggable
  },
  props: {
    height: {
      type: Number,
      default: 0
    },
    designer: {
      type: Object,
      default: null
    },
    /** 自定义显示组件，默认全部显示 */
    fields: {
      type: Array,
      default: null
    },
    /** 表单配置 */
    formConfig: {
      type: Object,
      default: null
    },
    /** 表单组件列表 */
    widgetList: {
      type: Array,
      default: () => []
    },
    /** 当前选中组件 */
    selected: {
      type: Object,
      default: () => {}
    }
  },
  emits: ['update:widgetList', 'update:selected'],
  setup(props, { emit }) {
    const { proxy } = getCurrentInstance()

    const leftTabs = ref('basic')
    const leftArea = ref(0)

    const jsonContent = computed({
      get() {
        const { widgetList, formConfig } = props
        return JSON.stringify({ widgetList, formConfig }, null, 2)
      }
      // set(value) {
      //   try {
      //     const parsed = JSON.parse(value)
      //     emit('update:widgetList', parsed)
      //   } catch (error) {
      //     proxy.$message.error('JSON格式错误，请检查后重试。')
      //   }
      // }
    })

    const panelHeight = computed(() => {
      return props.height + 'px'
    })

    const onlyCardName = (origin) => {
      if (origin.type !== 'card') {
        return false
      }
      return props.widgetList.some((v) => v.type === 'card')
    }

    const basicFieldsFilter = computed(() =>
      basicFields.filter((m) => {
        if (props.fields) {
          return props.fields.includes(m.type)
        }
        return true
      })
    )

    const complexFieldsFilter = computed(() =>
      complexFields.filter((m) => {
        if (props.fields) {
          // 过滤请假组件
          if (m.type === 'card' && m.options && m.options.name === 'leave') {
            return props.fields.includes(m.options.name)
          }
          return props.fields.includes(m.type)
        }
        return true
      })
    )

    const generateId = () => {
      return Math.floor(Math.random() * 100000 + Math.random() * 20000 + Math.random() * 5000)
    }

    /** 开始移动组件时触发，创建唯一ID */
    const handleFieldWidgetClone = (origin) => {
      if (onlyCardName(origin)) {
        proxy.$message.error(`不能重复添加自定义组件.`)
        return
      }

      const newWidget = _.cloneDeep(origin)
      newWidget.id = newWidget.type.replace(/-/g, '') + generateId()
      if (newWidget.type === 'card') {
        // 自定义组件
        if (!newWidget.options.name) {
          newWidget.options.name = newWidget.id
        }
        newWidget.components.forEach((item) => {
          item.id = item.type.replace(/-/g, '') + generateId()
          if (item.options.label === '') {
            item.options.label = item.name || item.type.toLowerCase()
          }

          if (!item.options.name) {
            item.options.name = item.id
          }
        })
      } else {
        if (origin.type === 'grid') {
          console.log('grid :>> ')
        } else {
          if (!newWidget.options.name) {
            newWidget.options.name = newWidget.id
          }
          if (newWidget.options.label === '') {
            newWidget.options.label = newWidget.name || newWidget.type.toLowerCase()
          }
        }
      }
      return newWidget
    }

    const addContainer = (origin) => {
      const newWidget = handleFieldWidgetClone(origin)
      if (newWidget) {
        // console.log('newWidget :>> ', newWidget)
        console.log('props.selected :>> ', props.selected)
        const list = props.widgetList.filter((x) => x.id)
        if (props.selected && props.selected.type === 'card') {
          const cardIndex = list.findIndex((x) => x.id === props.selected.id)
          if (cardIndex !== -1) {
            list[cardIndex].components.push(newWidget)
          } else {
            proxy.$message.error(`未找到对应的自定义组件，请刷新页面重试。`)
            return
          }
        } else {
          list.push(newWidget)
        }

        emit('update:widgetList', list)
        emit('update:selected', list[list.length - 1])
      }
    }

    return {
      leftTabs,
      leftArea,
      jsonContent,
      panelHeight,
      basicFieldsFilter,
      complexFieldsFilter,
      handleFieldWidgetClone,
      addContainer
    }
  }
}
</script>

<style lang="scss">
.ep-widget-panel-container {
  height: 100%;
  display: flex;
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
  width: 320px;

  .left-area {
    height: 100%;
    background: #fff;
    position: relative;
    border-right: 1px solid #e4e7ed;
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
    display: flex;
    flex-direction: column;
    text-align: center;
    padding-top: 20px;

    .left-area-icon {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 40px;
      height: 40px;
      font-size: 20px;
      color: #878f95;
      cursor: pointer;
      transition: 0.3s;
      margin-bottom: 8px;

      &.active {
        color: #409eff;
      }
    }
  }
  .left-panel-container {
    position: relative;
    padding: 10px;
  }

  .component-code-json {
    width: 258px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 4px;
    margin-top: 8px;
  }

  .component-description-list {
    padding: 0;
    &-content {
      padding-bottom: 24px;
      &-header {
        align-items: center;
        display: flex;
        justify-content: flex-start;
        .title {
          color: rgba(0, 0, 0, 0.6);
          font-family: PingFang SC, Hiragino Sans GB, Microsoft YaHei, Helvetica, Arial, sans-serif;
          font-size: 12px;
          font-weight: 700;
          line-height: 20px;
          padding-left: 8px;
        }
      }
      .widget-panel-fields {
        display: flex;
        flex-flow: row wrap;
        &-item {
          background: #fff;
          border: 1px solid #e5e6e8;
          border-radius: 6px;
          cursor: grab;
          margin: 8px 0 0 8px;
          position: relative;
          &:hover {
            border-color: #0089ff;
          }
          &:hover .title {
            color: #0089ff;
          }
          &:hover svg {
            fill: #0089ff;
          }
        }
      }

      .brief-snippet-inner {
        align-items: center;
        display: flex;
        height: 36px;
        padding: 0 8px;
        width: 117px;

        & > svg {
          height: 100%;
          margin-right: 8px;
          width: 14px;
        }
        .title {
          color: #171a1d;
          font-size: 12px;
          letter-spacing: 0;
          line-height: 18px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      .field-widget-item {
        display: flex;
        align-items: center;
        height: 28px;
        line-height: 28px;
        width: 48%;
        float: left;
        margin: 1%;
        padding: 0 10px;
        cursor: move;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        background: #f1f2f3;
        border: 1px solid #f4f6fc;
        .svg-icon {
          margin-right: 8px;
          font-size: 14px;
        }

        &:hover {
          background: #f4f6fc;
          outline: 1px solid #409eff;
        }
      }
    }
  }
}
</style>
